package leetcode.offer_two_special.backtrack;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @author mazouri
 * @create 2021-09-19 19:22
 */
public class _82_combinationSum2 {
    List<List<Integer>> res = new LinkedList<>();
    LinkedList<Integer> track = new LinkedList<>();
    int sum = 0;
    int target;
    int[] candidates;

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        this.candidates = candidates;
        this.target = target;
        Arrays.sort(this.candidates);
        backtrack(0);
        return res;
    }

    private void backtrack(int start) {
        if (sum == target) {
            res.add(new LinkedList<>(track));
            return;
        }

        for (int i = start; i < candidates.length; i++) {
            if (i > start && candidates[i] == candidates[i - 1]) continue;
            if (sum + candidates[i] > target) break;

            track.add(candidates[i]);
            sum += candidates[i];
            backtrack(i + 1);
            sum -= candidates[i];
            track.removeLast();
        }
    }
}
